package isea533.mybatis.servlet;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import isea533.mybatis.MybatisHelper;
import isea533.mybatis.mapper.CountryMapper;
import isea533.mybatis.model.Country;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class CountryServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        queryCountry(req, resp);
        req.getRequestDispatcher("index.jsp").forward(req, resp);
    }

    /**
     * 查询国家
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void queryCountry(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        SqlSession sqlSession = MybatisHelper.getSqlSession();
        CountryMapper countryMapper = sqlSession.getMapper(CountryMapper.class);
        try {
            PageHelper.startPage(req);
            List<Country> list = countryMapper.selectAll();
            PageInfo<Country> page = new PageInfo(list);
            req.setAttribute("page", page);
        } catch (Exception e) {
            req.setAttribute("err", "查询出错:" + e.getMessage());
        }
    }

}
